package com.woyao;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.ContactSummary;
import com.woyao.core.model.GetMyUserResponse;
import com.woyao.core.model.PartnerList;
import com.woyao.core.model.PartnerSummary;
import com.woyao.core.model.UserSummary;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class MyUserActivity extends AppCompatActivity {
    ProgressDialog progressDialog;

    private SearchView mSearchView;
    private ContentResolver cr;

    LinearLayout chosen_list;

    private ArrayList<UserSummary> current = new ArrayList<UserSummary>();


    private List<UserSummary> userItems = new ArrayList<UserSummary>();
    private UserSelectAdapter userAdapter;
    private RecyclerView userList = null;
    LinearLayoutManager userLayoutManager = null;
    private Boolean contactsLoaded = false;
    private Integer ADD_RELATION_CODE = 900;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_users);

        Toolbar toolbar = (Toolbar) findViewById(R.id.invite_toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        chosen_list = (LinearLayout)findViewById(R.id.user_chosen);

        userList = (RecyclerView)findViewById(R.id.user_items);
        userLayoutManager = new LinearLayoutManager(MyUserActivity.this);
        userLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        userList.setLayoutManager(userLayoutManager);
        userList.addItemDecoration(new DividerItemDecoration(MyUserActivity.this, DividerItemDecoration.VERTICAL_LIST));



        LinearLayout mobileContacts = (LinearLayout) findViewById(R.id.check_contactbook);

        mobileContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MyUserActivity.this, InviteActivity.class);

                startActivity(intent);
//                tryGetContacts();

            }
        });

        this.setTitle("选择合作伙伴");

        mSearchView = (SearchView) findViewById(R.id.user_search);
//        mSearchView.setVisibility(View.GONE);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                loadUser(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });



        Button finishBtn  = (Button) findViewById(R.id.id_users_finish);
        finishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                PartnerList kvl = new PartnerList();
                ArrayList<PartnerSummary> partners = new ArrayList<PartnerSummary>();
                for (  UserSummary oneUser : current ){
                    PartnerSummary ps = new PartnerSummary();
                    ps.setTitle( oneUser.getTitle());
                    ps.setUser_id(oneUser.getUser_id());
                    ps.setMobile("");
                    ps.setDisplayname(oneUser.getTitle());
                    ps.setSnailview(oneUser.getSnailview());
                    if (oneUser.getUser_id() > 0) {
                        ps.setDescription("尚未确认");
                    }else{
                        ps.setDescription("尚未注册");
                    }
                    partners.add(ps);
                }
                kvl.setContent(partners );
                intent.putExtra("partners", kvl  );
                setResult(666, intent);

                finish();
            }
        });

        Intent intent = getIntent();
        Integer theid = intent.getIntExtra("id", 0);
        Integer themid = intent.getIntExtra("mid", 0);

        loadUser("");
//        tryGetContacts();
    }



    public  void tryGetContacts() {
        contactsLoaded = true;
        if (ContextCompat.checkSelfPermission(MyUserActivity.this,android.Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions( MyUserActivity.this,
                    new String[]{android.Manifest.permission.READ_CONTACTS},
                    1);
            Log.i("woyaooo","'授权了吗？'");
        }else{
            getContacts();
        }




    }

    private void getContacts() {
        ArrayList<ContactSummary> contacts = new ArrayList<ContactSummary>();
        ArrayList<String> dups = new ArrayList<String>();
        try {

            cr = getContentResolver();
//            Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cs = null;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                cs = cr.query(uri, null, null, null,  "sort_key", null);
                StringBuilder sb = new StringBuilder();
                while (cs.moveToNext()) {
                    try {
                        //拿到联系人id 跟name
                        int id = cs.getInt(cs.getColumnIndex("_id"));

                        String number = cs.getString(cs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        number = number.replace(" ","").replace("+86","");

                        if (dups.contains( number ) ){
                            continue;
                        }
                        dups.add(number);
                        String name = cs.getString(cs.getColumnIndex("display_name"));



                        ContactSummary one = new ContactSummary();
                        one.setId(number);
                        one.setTitle(name  );
                        one.setDescription(number);
                        if (!one.getId().equals("") && !one.getTitle().equals("") && one.getId().length() == 11 && one.getId().startsWith("1") ){
                            contacts.add( one);
                        }

                        sb.append("displayname:" + name + ";");
                        sb.append("phone:" + number + ";");
                        sb.append("#");

                    }catch (Exception e){
                        Log.i("woyaooo", e.getMessage());
                    }
                }
                saveReload( sb.toString()) ;
//                Common.setProfileAttr("contacts", sb.toString());

            }

        }catch (Exception e){
            Toast.makeText(this,"不能访问通讯录", Toast.LENGTH_SHORT).show();
        }
    }


    public   void saveReload( final String content){
        progressDialog = new ProgressDialog(MyUserActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(userId,"contacts",content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                progressDialog.dismiss();
                if (success) {
                    loadUser("allusers");


                } else {

                }
            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);

    }

    public void loadUser( final String kw){

        AsyncTask<Void,Void, GetMyUserResponse> task1 =new AsyncTask<Void, Void, GetMyUserResponse>() {
            @Override
            protected GetMyUserResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyUserResponse> responseCall = svc.getMyUser(userId,kw);
                try {
                    GetMyUserResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyUserResponse response) {

                renderUser(response);
                if (!kw.equals("") && response.getContent().getItems().size() == 0){
                    Toast.makeText(MyUserActivity.this,response.getContent().getTitle(),Toast.LENGTH_LONG);
//                    new AlertDialog.Builder(MyUserActivity.this)
//                            .setTitle("")
//                            .setMessage(response.getMessage())
//                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    tryGetContacts();
//                                }
//                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    }).create().show();
                }



            }
            @Override
            protected void onCancelled() {

            }
        };
        task1.execute((Void)null);
    }
    private void renderUser(GetMyUserResponse response){

        userItems = response.getContent().getItems();
        TextView userSummary = findViewById(R.id.user_summary);
        userSummary.setText(response.getContent().getTitle());

        userAdapter = new UserSelectAdapter(MyUserActivity.this, userItems  );

        userAdapter.setChangedHandler(new UserSelectAdapter.Changed() {
            @Override
            public void view(UserSummary cs) {
                if (cs.getSelected()){
                    Boolean found = false;
                    for (UserSummary us : current){
                        if (cs.getUser_id()> 0) {
                            if (us.getUser_id() == cs.getUser_id()){
                                found = true;
                                break;
                            }
                        }else{
                            if (us.getMobile().equals( cs.getMobile()) ){
                                found = true;
                                break;
                            }
                        }
                    }
                    if (!found){
                        current.add(cs);
                    }
                }else{
                    int index = -1;
                    for (Integer i =0 ;i< current.size();i++){
                        UserSummary the_one = current.get(i);
                        if (cs.getUser_id()> 0) {
                            if (cs.getUser_id() == the_one.getUser_id()){
                                index = i;
                                break;
                            }
                        }else{
                            if (cs.getMobile().equals( cs.getMobile()) ){
                                index = i;
                                break;
                            }
                        }
                    }
                    if (index > -1 ){
                        current.remove(index);
                    }
                }
                refresh();

            }


        });

        userList.setAdapter(userAdapter);

    }

    private void refresh(){
        chosen_list.removeAllViews();
        for (UserSummary us : current){
            LinearLayout item = (LinearLayout) LayoutInflater.from(MyUserActivity.this).inflate(R.layout.user_chosen_item, null);
            CircleImageView snailview = (CircleImageView) item.findViewById(R.id.user_snailview);
            final TextView title = (TextView) item.findViewById(R.id.user_title);
            final TextView desc = (TextView) item.findViewById(R.id.user_info);

            if (StringUtil.notNullOrEmpty(us.getSnailview())) {
                Picasso.with(MyUserActivity.this)
                        .load(us.getSnailview())
                        .into(snailview);
            } else {
                snailview.setImageResource(R.drawable.no_avartar);
            }
            title.setText(us.getTitle());
            desc.setText(us.getDescription());
            chosen_list.addView(item);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i("woyaooo","'已经授权'");
                    getContacts();

                } else {
                    Log.i("woyaooo","'没有授权'");

                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        setResult(0, intent);
        finish();
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }
}
